<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    </style>
</head>
<body>
<div class="register-form-box-1">
    <form class="register-form-1">
        用户名：<input type="text" name="userName"/>
        密码：<input type="password" name="password"/>
    </form>
    <button class="submit-btn">提交</button>
</div>
<script>
    (function() {

        var strategies = {
            isNonEmpty: function(value, errorMsg) {
                if (value === '') {
                    return errorMsg;
                }
            },
            minLength: function(value, length, errorMsg) {
                if (value.length < length) {
                    return errorMsg
                }
            },
            isMobile: function(value, errorMsg) {
                if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
                    return errorMsg
                }
            }
        }

        var Validator = function() {
            this.cache = [];
        }

        Validator.prototype.add = function(dom, rule, errorMsg) {
            var ary = rule.split(':');
            this.cache.push(function() {
                var strategy = ary.shift();
                ary.unshift(dom.value);
                ary.push(errorMsg)

                return strategies[strategy].apply(dom, ary);
            })
        }

        Validator.prototype.start = function() {
            for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
                var msg = validatorFunc();
                if (msg) {
                    return msg;
                }
            }
        }


        var submit = document.querySelector('.submit-btn');
        var validataFunc = function() {
            var form = document.querySelector('.register-form-1');
            var validator = new Validator();
            validator.add(form.userName, 'isNonEmpty', '用户名不能为空');
            validator.add(form.password, 'minLength:6', '密码长度不能少于6位');
            var errorMsg = validator.start();
            return errorMsg;
        }

        submit.onclick = function() {
            var errorMsg = validataFunc();

            if (errorMsg) {
                console.log(errorMsg);
                return false
            }
        }
    })()
</script>
</body>
</html>